# -*- coding: utf-8 -*-

from naja_atra import WebsocketHandler, WebsocketRequest, WebsocketSession, WebsocketCloseReason
from naja_atra import websocket_handler, websocket_handshake, websocket_open, websocket_close, websocket_message
from naja_atra import WEBSOCKET_MESSAGE_TEXT
import naja_atra.utils.logger as logger

_logger = logger.get_logger("websocket")


@websocket_handler(endpoint="/ws/{path_val}")
class WSHandler(WebsocketHandler):

    def on_handshake(self, request: WebsocketRequest):
        path_val = request.path_values['path_val']
        _logger.info(f"on handshake, path val :: {path_val}")
        if path_val == "err":
            return 400, {"Self Defind Header": "Error!"}
        return None

    def on_open(self, session: WebsocketSession):

        _logger.info(f">>{session.id}<< open! {session.request.path_values}")

    def on_text_message(self, session: WebsocketSession, message: str):
        _logger.info(f">>{session.id}<< on text message: {message}")
        session.send(message)

    def on_close(self, session: WebsocketSession, reason: str):
        _logger.info(f">>{session.id}<< close::{reason}")


@websocket_handshake(endpoint="/ws-fun/{path_val}")
def ws_handshake(request: WebsocketRequest):
    return 0, {}


@websocket_open(endpoint="/ws-fun/{path_val}")
def ws_open(session: WebsocketSession):
    _logger.info(f">>{session.id}<< open! {session.request.path_values}")


@websocket_close(endpoint="/ws-fun/{path_val}")
def ws_close(session: WebsocketSession, reason: WebsocketCloseReason):
    _logger.info(
        f">>{session.id}<< close::{reason.message}-{reason.code}-{reason.reason}")


@websocket_message(endpoint="/ws-fun/{path_val}", message_type=WEBSOCKET_MESSAGE_TEXT)
async def ws_text(session: WebsocketSession, message: str):
    _logger.info(f">>{session.id}<< on text message: {message}")
    session.send(f"{session.request.path_values['path_val']}-{message}")
    if message == "close":
        session.close()
